package manager

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/api/admin/internal/model/pg"
	"navi-mumbai/common/auth"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/xerr"
	"strings"
	"time"

	"navi-mumbai/app/api/admin/internal/svc"
	"navi-mumbai/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.ManagerLoginReq, ip string) (resp *types.ManagerLoginResp, err error) {
	var mg *pg.Manager
	mg, err = l.svcCtx.ManagerModel.FindOne(l.ctx, req.Uid)
	if err != nil && err != pg.ErrNotFound {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	if err == pg.ErrNotFound || mg == nil {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.UserNotExist, "admin not found")
	}

	// log
	defer func() {
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return
		}

		loginLog := pg.LoginLog{
			Uid:         req.Uid,
			LoginDevice: req.Device,
		}
		if ip != "" {
			ips := strings.Split(ip, ",")
			if len(ips) > 0 {
				loginLog.LoginIp = ips[0]
			}
		}
		_, err2 := l.svcCtx.LoginLogModel.Insert(l.ctx, &loginLog)
		if err2 != nil {
			l.Logger.Errorf("insert login log error: %v", err2)
		}
	}()

	// compare password
	err = auth.CompareHashAndPassword(mg.Userpass, req.Password)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.AuthFail, "uid or password error")
	}

	resp = &types.ManagerLoginResp{
		Username:        mg.Username,
		PermissionLevel: mg.PermissionLevel,
		AllowApi:        mg.AllowApi,
	}

	// token
	resp.ExpiresIn = l.svcCtx.Config.JwtAuth.AccessExpire
	resp.Token, err = getJwtToken(l.svcCtx.Config.JwtAuth.AccessSecret, time.Now().Unix(), l.svcCtx.Config.JwtAuth.AccessExpire, mg.Uid, mg.PermissionLevel)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.TokenGenerateError, "token error")
	}

	//
	resp.PermissionDefine = l.svcCtx.Auth.GetPermissionDefine()

	// set admin api permission
	l.svcCtx.Auth.SetAdminApiPermission(mg.Uid, mg.AllowApi)
	return
}

func getJwtToken(secretKey string, iat, seconds int64, uid int64, permissionLevel int64) (string, error) {
	cl := make(map[string]interface{}, 0)
	cl[ctxdata.CtxKeyJwtUserId] = uid
	cl[ctxdata.CtxKeyJwtPermissionLevel] = permissionLevel

	return auth.GetJwtToken(secretKey, iat, seconds, cl)
}
